
<template>
  <div id="homeC" :class='{"isiphone":$isiphone,"zore":lesstwo<3}'>
    <div>
      <div class="top">
        <div class="one">
          <img src="../../../wechat/static/images/dzsc_logo.png" alt>
          <div class="cityBox" @click="showFilter('城市')">
            {{cityName?cityName:'城市'}}
            <img src="../../../wechat/static/images/dzsc_xl.png" alt>
          </div>
        </div>
        <div class="two" v-if="false">
          <a href="javascript:;" @click="showFilter('城市')">
            <span>{{cityName?cityName:'城市'}}</span>
            <img src="../../../wechat/static/images/dzsc_xl.png" alt>
          </a>
          <a href="javascript:;" @click="showFilter('商品分类')" :class='{"active":showClass}'>
            <span>商品分类</span>
            <img src="../../../wechat/static/images/dzsc_xl.png" alt>
          </a>
          <a href="javascript:;" @click="showFilter('品牌')" :class='{"active":showBrand}'>
            <span>品牌</span>
            <img src="../../../wechat/static/images/dzsc_xl.png" alt>
          </a>
        </div>
        <div class="three" v-if="false">
          <div class="hide" v-if="showClass">
            <checklist ref="classObject" 
            title
            :options="classifyList" 
            v-model="classifyVal" 
            label-position="left"
            @on-change="classifyChange"></checklist>
            <div class="hide-btn">
              <a href="javascript:;" @click="hideCancel(1)">取消</a>
              <a href="javascript:;" @click="hideprimary(1)">确定</a>
            </div>
          </div>
          <div class="hide" v-if="showBrand">
            <checklist ref="brandObject" 
            title
            :options="brandList" 
            v-model="brandId" 
            label-position="left"
            @on-change="brandChange"></checklist>
            <div class="hide-btn">
              <a href="javascript:;" @click="hideCancel(2)">取消</a>
              <a href="javascript:;" @click="hideprimary(2)">确定</a>
            </div>
          </div>
        </div>
        <div class="four">
          <div class="ulBox" :class='{"morethree":brandList.length>3}'>
            <div class="h4">品牌电子券 <span class="english"> BRAND VOUCHER</span>  <span style="color:#999;font-weight:500">{{(brandList.length==0&&brandload)?'（该城市暂无数据）':''}}</span></div>
            <ul>
              <li v-for="(item, index) in brandList"  :key="index" @click="Jumpbrand(item)">
                <div :style="{backgroundImage:'url(' + item.img + ')'}"></div>
              </li>
            </ul>
          </div>
          <div class="ulBox" :class='{"morethree":brandList2.length>3}'>
            <div class="h4">品牌配送<span class="english"> BRAND DISTRIBUTION</span>  <span style="color:#999;font-weight:500">{{(brandList2.length==0&&brandload)?'（该城市暂无数据）':''}}</span></div>
            <ul>
              <li v-for="(item, index) in brandList2" :key="index" @click="Jumpbrand(item)">
                <div :style="{backgroundImage:'url(' + item.img + ')'}"></div>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div class="middle" id='ul'>
        <p class='newTitle'>
          <span>最新上架</span>
          <i></i>
        </p>
        <ul>
          <li v-for="(item, index) in goodList" :key="index" @click="JumpItem(item)">
            <div class="img" :style="{backgroundImage:'url(' + item.img + ')'}"></div>
            <p>{{item.name}}</p>
            <span>¥ {{item.money}}</span>
          </li>
          <load-more :show-loading="false" tip="暂无更多数据" v-show="isNoData" background-color="#fbf9fe"></load-more>
          <load-more :show-loading="false" tip="数据加载中..." v-show="!isNoData" background-color="#fbf9fe"></load-more>
          <div class="tips-text">
            <p><a href="http://www.beian.miit.gov.cn">网站备案：粤ICP备19028417号-1</a> </p> 
          </div>
        </ul>
      </div>
      <tabbar>
        <tabbar-item selected>
          <img slot="icon" src="../../../wechat/static/images/tab_home_s.png">
          <span slot="label" style="font-family: PingFang-SC-Medium;
            font-size: 0.24rem;
            color: #ec1b24;">首页</span>
        </tabbar-item>
        <tabbar-item link="/centerC">
          <img slot="icon" src="../../../wechat/static/images/tab_grzx_n.png">
          <span slot="label" style="font-family: PingFang-SC-Medium;
            font-size: 0.24rem;
            color: #999999;">我的</span>
        </tabbar-item>
      </tabbar>
    </div>
    <div  @click="scrollTopBtn" class="top-icon">
      <img src="../../../wechat/static/images/top.png" alt="">
    </div>
  </div>
</template>

<script>
import cityList from "../../../wechat/static/util/city.json";
import { Tabbar, TabbarItem, Checklist, Scroller, LoadMore } from "vux";
export default {
  name: "homeC",
  data() {
    return {
      classifyList: [],
      goodList: [
      ],
      cityName: localStorage.getItem('cityName')|| '',
      cityCode: localStorage.getItem('cityCode')|| '',
      brandId: JSON.parse(localStorage.getItem('brandId'))||'', //品牌
      classifyVal: JSON.parse(localStorage.getItem('classifyVal')) ||'', //分类
      goodsName: "", //品牌名
      isOn: "y", //是否上架
      isOpen: "", //是否公开
      notOpenIds: "", //非公开商品id
      openIds: "", //公开商品id
      pageIndex: 1, //第几页
      pageSize: 10, //每页大小
      type: "", //类型
      onFetching: false,
      showClass: false,
      showBrand: false,
      classType: '',
      brandList: [],
      brandList2: [],
      isloading: false,
      brandload: false,
      isNoData: false,
      ul:document.getElementById('ul'),
    };
  },
  computed:{
    lesstwo(){
      return this.goodList.length
    },
  },
  activated(){
    // if(this.cityCode!=(localStorage.getItem('cityCode')||'')){
    //   this.init()
    // }
  },
  mounted() {
    
    this.init()
    let cityCode = localStorage.getItem('cityCode')||''
    let cityName = localStorage.getItem('cityName')||''
    // this.findEsCategoryByPage()
  },
  beforeCreate(){
    localStorage.setItem('userType','special')
  },
  created() {
    this.configSet()
  },
  methods: {
    configSet(){
      var pageUrl = window.location.href
      let url = `${this.$CONSTANT.WX.indexJsRequire}?url=${pageUrl}`;
      this.$common.post(url, {}, res => {
          if (res.status == 200) {
            let data = res.data.bussData;
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: data.appId, // 必填，公众号的唯一标识
                timestamp: data.timestamp, // 必填，生成签名的时间戳
                nonceStr: data.nonceStr, // 必填，生成签名的随机串
                signature: data.signature, // 必填，签名
                jsApiList: [
                        "checkJsApi", //判断当前客户端版本是否支持指定JS接口
                        "previewImage",
                        "onMenuShareTimeline", //分享到朋友圈
                        "onMenuShareAppMessage", //分享给朋友
                        "openLocation",
                        "getLocation",
                        "scanQRCode",
                        "chooseWXPay"
                    ] // 必填，需要使用的JS接口列表
            });
          } else {
            this.$vux.toast.show({
              text: res.msg,
              type: "warn",
              width: "auto"
            });
          }
        });
    },
    scrollTopBtn(){
      document.body.scrollTop=document.documentElement.scrollTop=0
    },
    init(){
      this.cityCode = localStorage.getItem('cityCode')||''
      this.cityName = localStorage.getItem('cityName')||''
      if(this.cityCode == 'undefined'){
        this.cityCode = ''
      }
      if(this.cityName == 'undefined'){
        this.cityName = ''
      }
      this.pageIndex = 1
      this.isloading = false
      this.isNoData = false
      this.brandload = false
      this.goodList = []
      this.getList()
      this.findEsBrandByPage()
      if(!this.cityCode||!this.cityName){
        this.getLocalData()
      }
    },
    getLocalData() {
      var that = this;
      console.log("开始定位");
      wx.getLocation({
        type: "wgs84", // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
        success: function(res) {
          console.log("获取当前定位：", res);
          var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
          var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
          var speed = res.speed; // 速度，以米/每秒计
          var accuracy = res.accuracy; // 位置精度
          var geocoder = new qq.maps.Geocoder({
            complete: function(result) {
              //解析成功的回调函数
              console.log("result");
              console.log(result);
              that.get3(result);
            }
          });
          geocoder.getAddress(new qq.maps.LatLng(latitude, longitude));
        },
        cancel: function (res) {
          console.log('wgs84cacel',res);
        },
        fail() {
          console.log("获取定位失败");
          that.cityName = "获取定位失败";
          // that.$vux.loading.show({
          //   text: "获取定位中"
          // });
          // setTimeout(() => {
          //     that.init()
          //     setTimeout(() => {
          //       that.$vux.loading.hide()
          //     }, 500);
          // }, 10);
        }
      });
    },
    get3(res) {
      if (res) {
        var province = res.detail.addressComponents.province;
        var city = res.detail.addressComponents.city;
        if (
          province == "北京市" ||
          province == "上海市" ||
          province == "天津市" ||
          province == "重庆市"
        ) {
          province = province.substr(0, 2);
        }
        this.getCode(province, city);
      } else {
        this.cityName = "获取定位失败";
        this.$vux.loading.show({
          text: "获取定位中"
        });
        setTimeout(() => {
            this.init()
            setTimeout(() => {
              this.$vux.loading.hide()
            }, 500);
        }, 10);
      }
    },
    getCode(province, city) {
      var provincesssssssss = cityList.provinces.province; //各省，直辖市
      provincesssssssss.forEach(element => {
        if (element.ssqname.indexOf(province) > -1) {
          if (
            province == "北京" ||
            province == "上海" ||
            province == "天津" ||
            province == "重庆"
          ) {
            this.cityName = province;
            this.cityCode = element.ssqid;
          } else {
            element.cities.city.forEach(element2 => {
              if (element2.ssqname.indexOf(city) > -1) {
                this.cityName = city;
                this.cityCode = element2.ssqid;
              }
            });
          }
        }
      });
      console.log(this.cityName);
      console.log(this.cityCode);
      localStorage.setItem('cityCode',this.cityCode)
      localStorage.setItem('cityName',this.cityName)
      this.$vux.loading.show({
        text: "获取定位中"
      });
      setTimeout(() => {
          this.init()
          setTimeout(() => {
            this.$vux.loading.hide()
          }, 500);
      }, 10);
    },
    Jumpbrand(item){
      localStorage.setItem('brandListDItem',JSON.stringify(item))
      this.$router.push('./brandListD?id='+item.key)
    },
    loadMore() {
      if(this.isNoData || this.isloading)return
      this.isloading = true;
      this.getList()
    },
    getList() {
      let url =
        this.$CONSTANT.GOODS.findEsGoodsByPage +
        "?sessionId=" +
        this.$common.getCookie("sessionId");
      let param = {
        city: this.cityCode,
        brandIds: this.brandId.length === 0?'':this.brandId, //品牌
        categoryIds: this.classifyVal.length === 0?'':this.classifyVal, //分类
        goodsName: this.goodsName, //品牌名
        isOn: this.isOn, //是否上架
        isUseRest: 'y',
        isOpen: this.isOpen, //是否公开
        notOpenIds: this.notOpenIds, //非公开商品id
        openIds: this.openIds, //公开商品id
        pageIndex: this.pageIndex, //第几页
        pageSize: this.pageSize, //每页大小
        type: this.type //类型
      };
      this.goodList = []
      console.log(param)
      // this.$vux.loading.show({
      //   text: "loading"
      // });
      this.$common.post(url, param, res => {
        this.isloading = false
        this.pageIndex++
        setTimeout(() => {
          this.$vux.loading.hide()
        }, 800);
        if (res.status == 200) {
          var bussData = res.data.bussData;
          bussData.forEach(element => {
            if(element.restNum>0){
              this.goodList.push({
                id: element.id,
                img: element.photos.length>0?element.photos[0].fileUrl:'',
                name: element.goodsName,
                money: element.price
              });
            }
            if(element.type=='real'&&element.modelPrice){
              let arr = element.modelPrice.split('::')
              let arr2 = []
              arr.map(item=>{
                let arr1 = item.split('&&')
                arr2.push({
                  name:arr1[0],
                  price:arr1[1]
                })
              })
              this.goodList[this.goodList.length-1].money=arr2[0].price
            }
          });
          this.isNoData = true
        } else {
          this.$vux.toast.show({
              text: res.msg,
              type: "warn",
              width: 'auto'
            });
        }
      });
    },
    hideprimary(type){
      this.showClass = false
      this.showBrand = false
      this.pageIndex = 1
      this.goodList= []
      this.isNoData = false
      this.getList()
    },
    hideCancel(type){
      if(type == 1){
        this.classifyVal = []
        setTimeout(() => {
          this.showClass = false
        }, 300);
      }else {
        this.brandId = []
        setTimeout(() => {
          this.showBrand = false
        }, 300);
      }
    },
    classifyChange(val, label) {
      console.log("change", val, label);
      console.log(this.classifyVal);
      localStorage.setItem('classifyVal',JSON.stringify(this.classifyVal))
    },
    brandChange(val, label) {
      console.log("change", val, label);
      localStorage.setItem('brandId',JSON.stringify(this.brandId))
    },
    showFilter(type) {
      if(type=='城市'){
        this.showClass = false
        this.showBrand = false
        this.$router.push('./chooseCityC')
      }else if(type =='商品分类'){
        this.showClass = !this.showClass
        this.showBrand = false
      }else{
        this.showClass = false
        this.showBrand = !this.showBrand
      }
    },
    JumpItem(item) {
      this.$router.push({ path: "/goodD", query: { id: item.id } });
    },
    findEsCategoryByPage() {
      let url =
        this.$CONSTANT.GOODS.findEsCategoryByPage +
        "?sessionId=" +
        this.$common.getCookie("sessionId");
      let param = {
        pageIndex: 1, //第几页
        pageSize: 100, //每页大小
      };
      this.$common.post(url, param, res => {
        if (res.status == 200) {
          var bussData = res.data.bussData;
          bussData.forEach(element => {
            this.classifyList.push({
              key: element.id,
              value: element.categoryName,
            });
          });
        } else {
          this.$vux.toast.show({
              text: res.msg,
              type: "warn",
              width: 'auto'
            });
        }
      });
    },
    findEsBrandByPage() {
      let userType = localStorage.getItem('userType')
      let url =
        this.$CONSTANT.GOODS.findEsBrandByPage +
        "?sessionId=" +
        this.$common.getCookie("sessionId");
      let param = {
        // cityCode: this.cityCode,
        pageIndex: 1, //第几页
        pageSize: 1000, //每页大小
        isCustomUser:userType == 'special'?'y':'',
        isNormalUser:userType == 'normal'?'y':'',
        cityCode:this.cityCode
      };
      this.$common.post(url, param, res => {
        this.brandload = true
        this.brandList2=[]
        this.brandList=[]
        if (res.status == 200) {
          var bussData = res.data.bussData;
            console.log('this.brandList1')
            console.log(this.brandList2)
            console.log(this.brandList)
          bussData.forEach(element => {
            if(element.type=='real'){
            console.log(2)
              //实物 品牌配送
              this.brandList2.push({
                key: element.id,
                value: element.brandName,
                img:element.photos[0].fileUrl 
              });
            }else if(element.type=='virtual'){
            console.log(1)
              //电子券
              this.brandList.push({
                key: element.id,
                value: element.brandName,
                img:element.photos[0].fileUrl 
              });
            }
          });
            console.log('this.brandList')
            console.log(this.brandList2)
            console.log(this.brandList)
        } else {
          this.$vux.toast.show({
              text: res.msg,
              type: "warn",
              width: 'auto'
            });
        }
      });
    },
  },
  components: {
    Tabbar,
    TabbarItem,
    Checklist,
    Scroller,
    LoadMore
  }
};
</script>

<style lang="less">
#homeC {
  min-height: 100%;
  background-color: #fff;
  .top {
    background: #fff;
    .one {
      padding: 0px 0 0px 11px;
      height: 53px;
      box-shadow: 3px 1px 3px #eae2e2;
      >img {
        height: 51%;
        width: 25.8%;
        position: relative;
        top: 15px;
        vertical-align: super;
      }
      .cityBox{
        display: inline;
        font-family: PingFang-SC-Medium;
        font-size: 15px;
        color: #333;
        cursor: pointer;
        margin-top: 15px;
        margin-right: 10px;
        position: relative;
        top: 3px;
        float: right;
        img{
          width: 8px;
          height: 5px;
          vertical-align: middle;
        }
      }
    }
    .two {
      padding: 0px 0 0px 11px;
      a {
        display: inline-block;
        background: #f7f7f7;
        border: 1px solid transparent;
        border-radius: 17px;
        text-align: center;
        width: 25.3%;
        height: 28px;
        line-height: 28px;
        margin-right: 10px;
        overflow: hidden;
        span {
          font-family: PingFang-SC-Medium;
          font-size: 13px;
          color: #999;
        }
        img {
          margin-left: 5px;
          width: 8px;
          height: 5px;
          vertical-align: middle;
          transition: .3s ease-in-out all;
          transform: rotateX(0deg);
        }
      }
      .active{
        img{
          transition: .3s ease-in-out all;
          transform: rotateX(180deg);
        }
      }
    }
    .three {
      // margin-top: 10px;
      .hide {
        >div{
          max-height: 200px;
          overflow-y: scroll;
        }
        .weui-cells_checkbox {
          &:before,
          &:after {
            border: none;
          }
          .weui-check_label {
            height: 53px;
            line-height: 53px;
            border-color: #e9e9e9;
            margin-right: 10px;
            margin: 0 10px 0 15px;
            padding: 0;
            .weui-cell__hd {
              padding-right: 0;
              .weui-icon-checked {
                &:before {
                  font-size: 17px;
                  color: #ec1b24;
                }
              }
            }
            .weui-cell__bd {
              p {
                color: #343434;
                font-family: PingFang-SC-Medium;
                font-size: 14px;
              }
            }
            border-bottom: 1px solid #e9e9e9;
            &:before {
              border: none;
            }
            &::after {
            }
          }
        }
        .hide-btn {
          // height: 99px;
          text-align: center;
          padding-top: 42px;
          padding-bottom: 23px;
          background: #fff;
          a {
            display: inline-block;
            height: 34px;
            width: 28.8%;
            line-height: 34px;
            text-align: center;
            border: 1px solid transparent;
            border-radius: 17px;
            font-family: PingFang-SC-Bold;font-weight: 600;
            font-size: 13px;
            &:first-child {
              background: #ededed;
              color: #999999;
            }
            &:last-child {
              margin-left: 10px;
              background: #ee3c4a;
              color: #fff;
            }
          }
        }
      }
    }
    .four{
      overflow: hidden;
      border-radius: 0px 0 20px 20px;
      padding-bottom: 14px;
      
      .ulBox{
        overflow: hidden;
        .h4{
          font-size:15px;
          font-family:PingFang SC;
          font-weight:500;
          color:rgba(51,51,51,1);
          height: 36.5px;
          line-height: 36.5px;
          padding-left: 11px;
          span{
            font-size:12px;
            font-family:PingFang SC;
            font-weight:500;
            color:rgba(153,153,153,1);
            margin-left: 7px;
          }
        }
        ul{
          display: -moz-box; /*Firefox*/
          display: -webkit-box; /*Safari,Opera,Chrome*/
          display: box;
          font-size: 0px;
          // height: 80px;
          margin-left: 10px;
          li{
            width: 96px;
            height: 96px;
            display: block;
            margin-right: 6.5px;
            overflow: hidden;
            div{
              width: 100%;
              height: 100%;
              object-fit: contain;
              background-size: 100% 100%;
            }
          }
        }
        &:last-child{
          h4{
            margin-top: 16px;
          }
        }
      }
      .morethree{
       ul{
          overflow-x: auto;
          -ms-overflow-style: none; //IE 10+
          overflow: -moz-scrollbars-none; //Firefox
          &::-webkit-scrollbar {
              display: none; //Safari and Chrome
          }
          li{
            // width: 29.3%;
            // height: 29.3%;
            // height: 110px;
            img{
            }
          }
        }
      }
    }
  }
  .middle {
    margin: 10px 0;
    margin-top: 0px;
    p.newTitle{
      height: 36px;
      line-height: 36px;
      padding: 0;
      text-align: center;
      background-color: #EDEDED;
      position: relative;
      font-size:15px;
      font-family:PingFang SC;
      font-weight:500;
      color:rgba(0,0,0,1);
      span{
        font-family: PingFang-SC-Bold;font-weight: 600;
        font-size: 15px;
        width: 85px;
        background: #EDEDED;
        position: absolute;
        left: 50%;
        font-family:PingFang SC;
        font-weight:500;
        color:rgba(0,0,0,1);
        margin-left: -42.5px;
        z-index: 99;;
      }
      i{
        position: relative;
        top: -3px;
        display: inline-block;
        height: 3px;
        width: 117px;
        background: rgba(0,0,0,1);
      }
    }
    ul {
      padding: 12px 10px 0 ;
      li {
        display: inline-block;
        width: 172.5px;
        background: #fff;
        border: 0px solid transparent;
        border-radius: 5px;
        margin-bottom: 10px;
        .img {
          display: inline-block;
          width: 172.5px;
          height: 172.5px;
          object-fit: contain;
          background-size: 100% 100%;
        }
        p {
          // padding: 12px;
          padding: 2.6%;
          text-overflow: -o-ellipsis-lastline;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          line-clamp: 2;
          -webkit-box-orient: vertical;
          font-family: PingFang-SC-Bold;font-weight: 600;
          color: #333;
          font-size: 14px;
          height: 34px;
          // height: 9%;
        }
        span {
          display: inline-block;
          font-family: PingFang-SC-Bold;font-weight: 600;
          color: #ea030b;
          font-size: 14px;
          margin: 0 12px 12px 12px;
        }
        &:nth-child(2n) {
          float: right;
        }
      }
    }
  }
  .weui-tabbar {
    position: fixed;
    .weui-tabbar__item {
      img {
        width: 21px;
        height: 21px;
        margin-top: 3px;
      }
    }
    .weui-bar__item_on {
      img {
        width: 23px;
        height: 21px;
      }
      .weui-tabbar__label {
        span {
          font-family: PingFang-SC-Medium;
          font-size: 12px;
          color: #ec1b24;
        }
      }
    }
    &:before {
      border: none;
    }
  }
}
</style>
